import { message } from 'antd'
import axios from 'axios'
import { getToken } from '.'
import { logout } from '@/store/actions/login'
import store from '../store'
import history from './history'

const instance = axios.create({
  baseURL: process.env.REACT_APP_URL,
  timeout: 5000,
})

instance.interceptors.request.use(
  (config) => {
    const token = getToken()
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

instance.interceptors.response.use(
  (response) => {
    return response
  },
  (err) => {
    if (!err.response) {
      message.error('网络繁忙，请稍后重试')
      return Promise.reject(err)
    }
    if (err.response.status === 401) {
      message.error('登录信息过期', 1)
      store.dispatch(logout())
      // history.push('/login')
      // #mark
      history.replace({
        pathname: '/login',
        state: {
          from: history.location.pathname,
        },
      })
    }
    return Promise.reject(err)
  }
)

export default instance
